import { cloneDeep } from "lodash";
import { computed, reactive, watch } from "vue";
import type { State } from "./typing";
import type { TableColumnsType, TableColumnType } from "ant-design-vue";

export const useColumns = (columns: TableColumnsType) => {
  const state: State = reactive({
    baseColumns: [],
    sortColumns: [],
    selectedKeys: [],
  });
  // 监听基础表格列处理
  watch(
    () => columns,
    (list) => {
      const arr = list.map((m) => {
        m.width = m.width || 120;
        m.ellipsis = "ellipsis" in m ? m.ellipsis : true;
        m.resizable = "resizable" in m ? m.resizable : true;
        if ((m as any).dataIndex === "operation") m.resizable = false;
        return m;
      });
      state.baseColumns = cloneDeep(arr);
      state.sortColumns = cloneDeep(arr);
      state.selectedKeys = arr.map(
        (m) => (m as TableColumnType).dataIndex as string
      );
    },
    { immediate: true, deep: true }
  );
  const dynamicColumns = computed<TableColumnsType>(() =>
    state.sortColumns.filter((f) =>
      state.selectedKeys.includes((f as TableColumnType).dataIndex as string)
    )
  );
  return { state, dynamicColumns };
};
